package com.wenhai.leetcode.search;

import java.util.Stack;

/**
 * @ClassName _173二叉搜索树迭代器
 * @Description https://leetcode-cn.com/problems/binary-search-tree-iterator/
 * @Author 谢文海
 * @Date 2021/3/28 15:39
 * @Version 1.0
 **/
public class _173二叉搜索树迭代器2 {
    private Stack<TreeNode> stack;
    private TreeNode cur;

    public _173二叉搜索树迭代器2(TreeNode root) {
        stack = new Stack<>();
        cur = root;
        push();
    }

    private void push() {
        while (cur != null) {
            stack.push(cur);
            cur = cur.left;
        }
    }


    public int next() {
        if (stack == null) {
            throw new IllegalStateException("Not Initializer TreeNodeIterator");
        }
        cur = stack.pop().right;
        int result = cur.val;
        push();
        return result;
    }

    public boolean hasNext() {
        return !stack.isEmpty();

    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
